package zekezang.org;

//import java.io.IOException;
//import java.io.InputStream;
//
//import org.apache.http.HttpHost;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpGet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import common.utils.activity.ActivityQueue;
import common.utils.activity.ActivityUtils;
import common.utils.database.FileControlUtils;
import common.utils.database.InitailDatabase;
import common.utils.net.DownloadNoStoreHandler;
import common.utils.net.fileDownloadReturnPathHandler;
import common.utils.properties.SharedPreferencesUtils;

//import common.utils.net.HttpsClientUtils;

public class WelcomeActivity extends Activity {
	/** Called when the activity is first created. */

	private static final String stringUrl = "http://10.0.161.67:8080/apkserver/3G-explorer.data";
	private static final String stringDataUrl = "http://10.0.161.67:8080/apkserver/explorer-data.data";
	private static final String updateUrl = "http://10.0.161.67:8080/apkserver/123.apk";

	private ProgressBar myWelcomeProgressBar = null;

	private Handler updatahandler = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityUtils.getInstance().setFullScreen(this);
		setContentView(R.layout.welcome_log);
		ActivityQueue.activityList.add(this);

		checkNetState();

//		SharedPreferencesUtils.setSharedPref(this, "full_screen", "yes");

//		 初始化声音Utils
//		SoundPoolUtils.getInstance(this);

		// 初始化数据库
		InitailDatabase.getInstance().initDB(this);

		// 初始化版本
//		TextView hakka_version = (TextView) this.findViewById(R.id.hakka_version);
//		ActivityUtils.getInstance().initVersion(this, hakka_version);

		myWelcomeProgressBar = (ProgressBar) findViewById(R.id.myWelcomeProgressBar);

		final String mainweb = setMainWeb();

		// 两秒后跳转
		Handler handler = new Handler(Looper.myLooper()) {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 1) {
					myWelcomeProgressBar.setProgress(80);
					if (msg.obj.equals("error") || msg.obj == null) {
						ActivityUtils.getInstance().netSpeedSlowly(WelcomeActivity.this, WelcomeActivity.this);
					} else {
						if (mainweb != null) {
							ActivityUtils.getInstance().leftIN_rightOUT_Transition(WelcomeActivity.this, WelcomeActivity.this, WebviewActivity.class,
									"uri", mainweb);
							WelcomeActivity.this.finish();
						} else {

							myWelcomeProgressBar.setProgress(100);

							final String s = msg.obj.toString();
							
//							Log.i("zekezang","eee:"+s);
							if (s != null && !s.equals("") && s.length() > 0) {

								HashMap<String, String> map = new HashMap<String, String>();
								FileControlUtils.getInstance().getStringList(s, map);
								String apkUpdateDate = map.get("apkUpdateDate");
								String apkUpdateDates = SharedPreferencesUtils.getSharedPref(WelcomeActivity.this, "apkUpdateDate");
								Date dateRemote = null; 
								Date dateLocal = null;
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								try {
									dateRemote = sdf.parse(apkUpdateDate);
									if(apkUpdateDates.equals("zekezang")){
										apkUpdateDates = sdf.format(new Date());
									}
									dateLocal = sdf.parse(apkUpdateDates);
								} catch (ParseException e) {
									Log.e("zekezang",e.getMessage());
								}
								if (dateLocal.compareTo(dateRemote)<0) {
									SharedPreferencesUtils.setSharedPref(WelcomeActivity.this, "apkUpdateDate", apkUpdateDate);
									update(s);
								} else {
								}
							}
						}
					}
				}
				
				if(msg.what == 2){
					String navigate = msg.obj.toString();
					ActivityUtils.getInstance().leftIN_rightOUT_Transition(WelcomeActivity.this, WelcomeActivity.this,
							MainActivity.class, "navigate", navigate);
					WelcomeActivity.this.finish();
				}
			}
		};

		myWelcomeProgressBar.setProgress(10);
//		handler.postDelayed(new DownloadNoStoreHandler("http://i.roboo.com/3G-explorer.data", handler, 1), 1000);
		handler.postDelayed(new DownloadNoStoreHandler(stringUrl, handler, 1), 5000);
		handler.postDelayed(new DownloadNoStoreHandler(stringDataUrl, handler, 2), 1000);

	}

	private void update(final String s) {
		registerReceiver();
		initUpdataHandler();
		showUpdateDialog(s);
	}

	private UpdateReceiver updateReceiver = null;

	private void registerReceiver() {
		updateReceiver = new UpdateReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("zekezang.update.receiver");
		WelcomeActivity.this.registerReceiver(updateReceiver, intentFilter);
	}

	private void showUpdateDialog(final String s) {
		AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);
		builder.setTitle("版本更新");
		builder.setMessage("有新版本啦! 更新吗?");
		builder.setNegativeButton("是", new DialogInterface.OnClickListener() {// 退出按钮
					@Override
					public void onClick(DialogInterface dialog, int i) {
						updatahandler.postDelayed(new fileDownloadReturnPathHandler(updateUrl, updatahandler, "updata-3g-explorer.apk"), 1000);
						ActivityUtils.getInstance().leftIN_rightOUT_Transition(WelcomeActivity.this, WelcomeActivity.this, MainActivity.class,
								"dataStr", s);
//						WelcomeActivity.this.finish();
					}
				});
		builder.setPositiveButton("否", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				ActivityUtils.getInstance().leftIN_rightOUT_Transition(WelcomeActivity.this, WelcomeActivity.this, MainActivity.class, "dataStr", s);
				WelcomeActivity.this.unregisterReceiver(updateReceiver);
				WelcomeActivity.this.finish();
			}
		});
		AlertDialog dialog = builder.create();
		if (dialog.isShowing()) {
			dialog.dismiss();

		}
		dialog.show();// 显示对话框
	}

	private void initUpdataHandler() {
		updatahandler = new Handler(Looper.myLooper()) {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);

				System.out.println(String.valueOf(msg.obj));
				// 发送广播
				Intent intent = new Intent();
				intent.putExtra("path", String.valueOf(msg.obj));
				intent.setAction("zekezang.update.receiver");
				WelcomeActivity.this.sendBroadcast(intent);

			}
		};
	}

	private String setMainWeb() {
		String mainweb = null;
//		String sql = "select uri from book where mainWeb = 1";
//		SQLiteDatabase sqLiteDatabase = new DatabaseHelper(this, "book_DB").getReadableDatabase();
//		try {
//			Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[] {});
//			while (cursor.moveToNext()) {
//				mainweb = cursor.getString(cursor.getColumnIndex("uri"));
//			}
//			cursor.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			sqLiteDatabase.close();
//		}
		String s = SharedPreferencesUtils.getSharedPref(this, "main_page");
		if (s.equals("zekezang")) {
			return mainweb;
		} else {
			mainweb = s;
			return mainweb;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onRestart();
		int[] i = ActivityUtils.getInstance().getWidthHight(this);
		RelativeLayout.LayoutParams params = (LayoutParams) myWelcomeProgressBar.getLayoutParams();
		params.width = i[0] - 60;
		params.leftMargin = 30;
		params.topMargin = i[1] - i[1] / 6;

	}

	private void checkNetState() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo == null) {
			ActivityUtils.getInstance().noNetWork(WelcomeActivity.this, WelcomeActivity.this);
		} else {
			System.out.println("connectted");
			// connect
		}
//		NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	}
//	private String entityToString(InputStream inputStream){
//		StringBuffer sb = new StringBuffer();
//		try {
//			int i = 0;
//			byte[] b = new byte[1024];
//			
//			while((i=inputStream.read(b)) != -1){
//				sb.append(new String(b, 0, i, "UTF-8"));
//			}
//		} catch (IOException e) {
//		}
//		return sb.toString().trim();
//	}

	// --------------------------------
//	HttpsClientUtils clientUtils = new HttpsClientUtils();
//	
//	HttpHost host = new HttpHost("180.153.19.120",8443,"https");
//	
//	HttpClient httpClient = clientUtils.getHttpsClient(host, "admin", "cloudroot123");
//	HttpGet httpGet = new HttpGet("https://180.153.19.120:8443/cloud/api/workloads");
//	
//	HttpResponse response = null;
//	try {
//		response = httpClient.execute(host, httpGet);
//		String s = entityToString(response.getEntity().getContent());
//		
//		System.out.println(s);
//	} catch (ClientProtocolException e) {
//		e.printStackTrace();
//	} catch (IOException e) {
//		e.printStackTrace();
//	}

	// --------------------------------

}